package controller;

import java.util.Locale;
import java.util.ResourceBundle;

import gameapi.Player;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;


import db.RegisteredUserDb;



@ManagedBean
@SessionScoped
public class LoginController {
	private RegisteredUserDb userDatabase = RegisteredUserDb.getInstance();
	@ManagedProperty(value = "#{player}")
	private Player player;
	private static final String TABLEVIEW = "/table.xhtml";
	private UIComponent loginButton;
	@ManagedProperty(value="#{gameController}")
	private GameController gameController;
	
	private static Logger logger = Logger.getLogger(LoginController.class);
	


	public LoginController() {
		
	}
	public String login(){
		String goToView = "";
		try {
			if(userDatabase.loginPlayer(player)){
				goToView = TABLEVIEW;
				logger.debug("Aufruf gameController.setPlayer "+player.getUserName());
				//gameController =  new GameController();
				
				gameController.setPlayer(player);
				gameController.joinPlayer(player);
			}
		} catch (Exception e) {			
			FacesContext context = FacesContext.getCurrentInstance();

			Locale language = context.getViewRoot().getLocale();
			ResourceBundle res = ResourceBundle.getBundle("i18n", language);
			
			
			String message = (String) res.getObject("playernotregistered");

			
			
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN,
					message, null);

			context.addMessage(loginButton.getClientId(context), msg);
		}
		
		return goToView;
	}
	
	public Player getPlayer(){
		return this.player;
	}
	
	public void setPlayer(Player player){
		this.player = player;
	}
	
	public void setLoginButton(UIComponent component){
		this.loginButton = component;
	}
	public UIComponent getLoginButton(){
		return loginButton;
	}
	public GameController getGameController() {
		return gameController;
	}
	public void setGameController(GameController gameController) {
		this.gameController = gameController;
	}
}
